package com.wnn.demo.model.hospital.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wnn.demo.domain.Department;
import com.wnn.demo.model.hospital.mapper.DepartmentMapper;
import com.wnn.demo.utils.IdWorker;
import com.wnn.demo.utils.MyStringUtil;
import com.wnn.demo.vo.DeptTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.*;

import java.util.*;
import java.sql.Timestamp;
import java.util.stream.Collectors;


/**
 * 部门管理
 * @author asus
 */
@Service
public class DepartmentService {

    @Autowired
    private   DepartmentMapper departmentMapper;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查找所有部门信息
     * @param page
     * @param limit
     * @return
     */
    public PageInfo< List > selectDepartmentAll(Integer type ,Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        List info = departmentMapper.selectDepartmentAll(type);
        return new PageInfo<List>(info);
    }

    /**
     * 新增部门
     * @param department
     * @return
     */
    public int insertDepartment(Department department) {
        String id = idWorker.nextId() + "";
        Date date = new Date();          // 获取一个Date对象
        Timestamp timeStamp = new Timestamp(date.getTime());
        //处理父级
        String parentId = department.getParentId();
        if (parentId ==null||"".equals(parentId) ){
            parentId = "0";
        }
        department.setDepartmentId(id);
        department.setParentId(parentId);
        department.setCreateTime(timeStamp);
        int i = departmentMapper.insert(department);
        return i;
    }

    /**
     * 更新部门
     * @param department
     * @return
     */
    public int updateDepartment(Department department) {
        Example example=new Example(Department.class);
        example.createCriteria().andEqualTo("departmentId",department.getDepartmentId());
        //处理父级
        String parentId = department.getParentId();
        if (parentId ==null||"".equals(parentId) ){
            parentId = "0";
        }
        department.setParentId(parentId);

        return departmentMapper.updateByExampleSelective(department,example);

    }

    public int deleteDepartmentById(String id) {
        int i = departmentMapper.deleteByPrimaryKey(id);
        return i;
    }

    public int batchDepartmentByIds(String ids) {
        return departmentMapper.deleteByIds(ids);
    }

    public List< Department > findParentDept() {
        Example example = new Example(Department.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId","0");
        return  departmentMapper.selectByExample(example);
    }

    public List< Map > findDeptTree() {
        return null;
    }

    /**
     * 获取所有部门-科室的dtree树
     * @return
     */
    public List< DeptTreeVo > selectDeptTreeList(String hospitalId,String employeeId,String isCheckArr,String isNotChoose) {
        List< DeptTreeVo > allDeptList = departmentMapper.selectDeptTreeList(hospitalId,employeeId,isCheckArr);
        for (DeptTreeVo d:allDeptList) {
            if (d.getCheckArr()==null){
                d.setCheckArr("0");
            }
            //只要不被选中的树结构
            if ("yes".equals(isNotChoose)){
                d.setCheckArr("0");
            }
        }
        List< DeptTreeVo > firstDeptTree = allDeptList.stream().filter(d -> "0".equals(d.getParentId())).collect(Collectors.toList());
        for (DeptTreeVo fd:firstDeptTree
             ) {
            String deptId = fd.getId();

            ArrayList< DeptTreeVo > childDeptTreeList = new ArrayList<>();
            for (DeptTreeVo childDept:allDeptList
            ) {
                String childDeptParentId = childDept.getParentId();
                if (childDeptParentId.equals(deptId)){
                    childDeptTreeList.add(childDept);
                    //如果是员工使用该接口  树结构选中了子类科室，让父结构部门也选中
                    if (!MyStringUtil.isNullOrEmpty(employeeId) && "1".equals(childDept.getCheckArr()) ){
                        fd.setCheckArr("1");
                    }
                }
            }
            fd.setChildren(childDeptTreeList);
        }
        return firstDeptTree;
    }

    /**
     *  给医院分配拥有的部门
     */
    @Transient
    public int updateHospitalHaveDeptList(String hospitalId, String deptViewIds) {

        List< Department > hospitalHaveDeptList = departmentMapper.selectDeptByHospitalId(hospitalId);
        //前端传递更改的ids列表
        ArrayList< String > deptIds = new ArrayList<>();
        if (MyStringUtil.isNullOrEmpty(deptViewIds)){
          deptIds.add("");
        }else {
            deptIds = new ArrayList<>(Arrays.asList(deptViewIds.split(",")));
        }
        //查询数据库医院已经有的 部门ids列表
        ArrayList< String > deptIdsDB = new ArrayList<>();
        for (Department haveDept:hospitalHaveDeptList
             ) {
            String haveDeptId = haveDept.getDepartmentId();
            deptIdsDB.add(haveDeptId);
        }
        //创建对比的新增列表和删除列表
//        ArrayList< String > deleteIds = new ArrayList<>();
//        ArrayList<  String > insertIds = new ArrayList<>();
        // 对比获得删除ids
        for (String deptId: deptIdsDB
        ) {
            // contains 包含方法  deptIds为前端ids列表；contains中为一个字符串
            if (!deptIds.contains(deptId)){
//                deleteIds.add(deptId);
                departmentMapper.deleteHospAndDept(hospitalId,deptId);
            }
        }
        //对比获取增加ids
        for (String deptId: deptIds
        ) {
            if ( !MyStringUtil.isNullOrEmpty(deptId) && !deptIdsDB.contains(deptId)){
//                insertIds.add(deptId);
                String hdId = idWorker.nextId() + "";
                departmentMapper.insertHospAndDept(hdId,hospitalId,deptId);
            }
        }
        return 1;
    }
}
